package com.maxjay.system.bo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

import com.maxjay.common.exception.ERR;
import com.maxjay.common.exception.GeneException;
import com.maxjay.system.po.TSysRole;
import com.maxjay.system.po.TSysUser;

/**
 * 用户信息类
 * 
 * @author Administrator
 *
 */
public class UserInfo extends TSysUser implements UserDetails {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static String SYS_USERINFO = "SYS_USERINFO";

	private Set<String> functions = new HashSet<String>(0);
	
	private Set<TSysRole> roles = new HashSet<TSysRole>(0);
	
	public UserInfo() {

	}

	public UserInfo(TSysUser user) {
		init(user);
	}
	
	public static UserInfo initFrom(TSysUser user){
		return new UserInfo(user);
	}
	
	public void refresh(TSysUser user){
		init(user);
	}
	
	private void init(TSysUser user){
		try {
			BeanUtils.copyProperties(this, user);
		} catch (Exception e) {
			e.printStackTrace();
			throw GeneException.getGeneException(ERR.ERROR_ERR_MSG, e);
		}
	}

	public boolean authorFunction(String function) {
		return functions.contains(function);
	}

	public Set<String> getFunctions() {
		return functions;
	}

	public void setFunctions(Set<String> functions) {
		this.functions = functions;
	}
	
	public void addFunction(String function){
		this.functions.add(function);
	}

	@Override
	public Collection<GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());
    	for(TSysRole role : roles) {
    		grantedAuthorities.add(new GrantedAuthorityImpl(role.getRoleId()));
    	}
        return grantedAuthorities;
	}

	@Override
	public String getUsername() {
		return this.getLoginId();
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}
	
	@Override
	public boolean isEnabled() {
		return true;
	}
	
	public String getBusinessEmail() {
		return this.getEmail();
	}

	public String getFamilyName() {
		return null;
	}

	public String getId() {
		return this.getObjId();
	}

	public Set<TSysRole> getRoles() {
		return roles;
	}

	public void setRoles(Set<TSysRole> roles) {
		this.roles = roles;
	}
	
}
